package com.ilarele.shopping.server;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class DownloadImage implements Runnable {
	private Socket socket;

	public DownloadImage(Socket socket) {
		System.out.println("will receive an image");
		this.socket = socket;
		new Thread(this).start();
	}

	@Override
	public void run() {
		DataInputStream dis = null;
		ObjectOutputStream oos = null;
		FileOutputStream fout = null;
		ObjectInputStream ois = null; // TODO close
		try {
			// recv name
			ois = new ObjectInputStream(socket.getInputStream());
			String picName = (String) ois.readObject();
			System.out.println("recv pic named " + picName);
			
			// recv pic
			dis = new DataInputStream(socket.getInputStream());
			oos = new ObjectOutputStream (socket.getOutputStream());
			File newPath = new File(ConnectionConstants.PICTURES_FOLDER, picName);
			
			fout = new FileOutputStream(newPath);
			int i;
			
			while ((i = dis.read()) > -1) {
				fout.write(i);
			}
			oos.writeObject(newPath.getPath());
			System.out.println("image received, send path " + newPath.getName());
			fout.flush();
			fout.close();
			dis.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (fout != null)
					fout.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				if (dis != null)
					dis.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				if (oos != null)
					oos.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
